package com.di3fang.gateway.config.security.access;

import com.alibaba.fastjson.JSONObject;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 当用户尝试访问安全的资源而不提供任何凭据时，将调用此方法发送401 响应
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        Object exception = request.getAttribute("exception");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("errorcode", HttpServletResponse.SC_UNAUTHORIZED);
        jsonObject.put("errormsg", exception == null ? "Unauthorized" : exception);
        response.getWriter().write(JSONObject.toJSONString(jsonObject));
    }
}
